{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Создать тест</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <link rel="stylesheet" href="{% static 'main/css/tests.css' %}" />
</head>
<body>
    <div class="container">
        <form method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="test_form">
                <div class="test_left_menu">
                    <h1>Создать тест</h1>
                    {{ form.as_p }}
                    <button type="submit" class="btn btn-primary">Сохранить тест</button>
                </div>
    
                <div class="test_right_menu">
                    <h2>Задания</h2>
                    {{ formset.management_form }}
                    <div id="tasks">
                        {% for form in formset %}
                            <div class="task-form">
                                {{ form.as_p }}
                            </div>
                        {% endfor %}
                    </div>
                    <button type="button" class="btn btn-secondary" id="add-task">Добавить задание</button>
                </div>
            </div>
        </form>
    </div>

    <script>
        $(document).ready(function() {
            function updateTaskLabels() {
                $('#tasks .task-form').each(function(index) {
                    $(this).find('label[for*="title"]').text('Заголовок задания ' + (index + 1) + ':');
                });
            }

            $('#add-task').click(function() {
                var formIdx = $('#id_tasks-TOTAL_FORMS').val();
                var formHtml = $('.task-form:first').clone().find(':input').each(function() {
                    var name = $(this).attr('name').replace(/-\d+-/, '-' + formIdx + '-');
                    var id = $(this).attr('id').replace(/-\d+-/, '-' + formIdx + '-');
                    $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
                }).end().find('label').each(function() {
                    var newFor = $(this).attr('for').replace(/-\d+-/, '-' + formIdx + '-');
                    $(this).attr('for', newFor);
                }).end();

                $('#tasks').append(formHtml);
                $('#id_tasks-TOTAL_FORMS').val(parseInt(formIdx) + 1);

                updateTaskLabels();
            });
            

            $('.task-form p').each(function() {
                if (!$(this).find('input[type="checkbox"]').length) {
                    $(this).css('display', 'grid');
                }
            });

            updateTaskLabels();
        });
    </script>
</body>
</html>
